//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.quickserver.net.qsadmin;

import java.awt.Robot;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Logger;
import org.quickserver.net.server.QuickServer;
import org.quickserver.util.MyString;

public class QSAdminShell extends Thread {
    private static Logger logger = Logger.getLogger(QSAdminShell.class.getName());
    private String promptName = "QSAdmin";
    private String promptPostFix = ":> ";
    private String prompt;
    private String error;
    private BufferedReader in;
    private String command;
    private Socket clientSocket;
    private QuickServer server;
    private InputStream s_in;
    private OutputStream s_out;
    private BufferedReader s_br;
    private BufferedOutputStream s_bo;
    private boolean gotResponse;
    private boolean multilineResponse;
    private boolean stop;
    private static QSAdminShell qsAdminShell;
    private static long oldMaxClient = -1L;

    public static QSAdminShell getInstance(QuickServer server, String promptName) {
        if (qsAdminShell == null) {
            if (server == null) {
                return null;
            }

            qsAdminShell = new QSAdminShell(server, promptName);
            qsAdminShell.start();
        } else {
            if (server != null) {
                qsAdminShell.server = server;
            }

            if (promptName != null) {
                qsAdminShell.promptName = promptName;
            }

            qsAdminShell.stop = false;
        }

        return qsAdminShell;
    }

    private QSAdminShell(QuickServer server, String promptName) {
        super("GUIAdminShell");
        this.prompt = this.promptName + this.promptPostFix;
        this.error = "Error: ";
        this.command = "";
        this.clientSocket = null;
        this.stop = false;
        this.setDaemon(true);
        this.server = server;
        if (promptName != null) {
            this.setPromptName(promptName);
        }

        boolean isConsole = true;

        try {
            if (System.console() == null) {
                isConsole = false;
            }
        } catch (Throwable var6) {
            ;
        }

        if (isConsole) {
            try {
                this.in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
            } catch (UnsupportedEncodingException var5) {
                logger.warning("UTF-8 was not supported: " + var5);
                this.in = new BufferedReader(new InputStreamReader(System.in));
            }

            logger.fine("Starting QSAdmin Shell");
        } else {
            System.out.println("QuickServer: System does not have console so not starting QSAdmin Shell!");
        }

    }

    public void setPromptName(String name) {
        if (name != null) {
            this.promptName = name;
            this.prompt = this.promptName + this.promptPostFix;
        }
    }

    public String getPromptName() {
        return this.promptName;
    }

    public void stopShell() throws IOException {
        this.stop = true;
        this.clientSocket.close();
    }

    public void run() {
        if (this.in == null) {
            logger.warning("We do not have System.in.. So stopping QSAdminShell.");
        } else {
            try {
                for(int i = 0; i < 3; ++i) {
                    sleep(500L);
                    if (!this.server.getQSAdminServer().getServer().isClosed()) {
                        this.connect();
                        break;
                    }

                    if (i == 3) {
                        logger.warning(this.error + "QSAdminServer is not running!! So stopping QSAdminShell.");
                        return;
                    }
                }
            } catch (Exception var4) {
                logger.fine(this.error + var4.getMessage());
            }

            while(!this.stop) {
                try {
                    this.print(this.prompt);
                    this.command = this.in.readLine();
                    if (this.stop) {
                        if (!this.command.trim().equals("")) {
                            System.out.println("Command ignored since shell was closed.");
                        }
                        break;
                    }

                    if (this.command == null) {
                        System.out.println("");
                        logger.severe("User must have forced an exit at shell!");
                    } else if (this.command.equals("FullThreadDump")) {
                        tryFullThreadDump();
                    } else {
                        if (this.command.toLowerCase().startsWith("disconnect")) {
                            try {
                                this.clientSocket.close();
                                this.s_bo.close();
                                this.s_br.close();
                            } catch (Exception var2) {
                                this.println("-ERR " + var2);
                            }
                            break;
                        }

                        if (!this.command.trim().equals("")) {
                            if (this.clientSocket != null || this.connect()) {
                                this.sendCommand(this.command);
                            }
                        } else if (this.clientSocket == null) {
                            this.connect();
                        }
                    }
                } catch (Exception var3) {
                    this.println("-ERR " + var3);
                }
            }

            qsAdminShell = null;
        }
    }

    private void print(String text) {
        System.out.print(text);
    }

    private void println(String text) {
        System.out.println(text);
    }

    private boolean connect() throws IOException {
        try {
            this.server.getQSAdminServer().getServer().nextClientIsTrusted();
            int port = this.server.getQSAdminServer().getServer().getPort();
            String host = this.server.getQSAdminServer().getServer().getBindAddr().getHostAddress();
            this.connect(host, port);
            return true;
        } catch (Exception var4) {
            this.println(this.error + var4.getMessage());
            logger.warning(MyString.getStackTrace(var4));
            if (this.clientSocket != null) {
                try {
                    this.clientSocket.close();
                } catch (Exception var3) {
                    ;
                }

                this.clientSocket = null;
            }

            return false;
        }
    }

    private void connect(String host, int port) throws IOException {
        this.clientSocket = new Socket(host, port);
        this.clientSocket.setSoTimeout(0);
        this.s_in = this.clientSocket.getInputStream();
        this.s_out = this.clientSocket.getOutputStream();
        this.s_br = new BufferedReader(new InputStreamReader(this.s_in, "UTF-8"));
        this.s_bo = new BufferedOutputStream(this.s_out);
        String temp = null;
        temp = this.s_br.readLine();
        temp = this.s_br.readLine();
        temp = this.s_br.readLine();
        if (oldMaxClient == -1L) {
            try {
                long maxC = -1L;
                this.sendCommand("get self maxClient", false);
                temp = this.s_br.readLine();
                maxC = Long.parseLong(temp.substring(4));
                if (maxC != -1L && maxC != 0L) {
                    oldMaxClient = maxC++;
                    this.sendCommand("set self maxClient " + maxC, false);
                    temp = this.s_br.readLine();
                    if (!temp.startsWith("+OK")) {
                        this.println(this.error + "Could not increase max client from QSAdmin : " + this.s_br);
                    }
                }
            } catch (IOException var6) {
                throw var6;
            } catch (Exception var7) {
                this.println(this.error + var7.getMessage());
            }
        }

        this.startSocketListener();
    }

    private synchronized void sendCommand(String command) throws IOException {
        this.sendCommand(command, true);
    }

    private synchronized void sendCommand(String command, boolean wait) throws IOException {
        if (this.clientSocket == null) {
            this.println(this.error + "Not connected yet");
        }

        command = command + QuickServer.getNewLine();
        this.gotResponse = false;
        byte[] d = command.getBytes();
        this.s_bo.write(d, 0, d.length);
        this.s_bo.flush();

        try {
            while(wait && !this.gotResponse) {
                sleep(100L);
            }
        } catch (InterruptedException var5) {
            logger.fine(this.error + var5.getMessage());
        }

    }

    public void startSocketListener() {
        String pad = "";
        Thread t = new Thread() {
            public void run() {
                String rec = "";

                while(true) {
                    try {
                        rec = QSAdminShell.this.s_br.readLine();
                    } catch (IOException var4) {
                        QSAdminShell.logger.info("Shell Closed! " + var4.getMessage());
                        break;
                    }

                    if (rec == null) {
                        QSAdminShell.this.clientSocket = null;
                        break;
                    }

                    if (rec.equals("+OK info follows")) {
                        QSAdminShell.this.multilineResponse = true;
                    }

                    QSAdminShell.this.println(rec);
                    if (!QSAdminShell.this.multilineResponse) {
                        QSAdminShell.this.gotResponse = true;
                    } else if (rec.equals(".")) {
                        QSAdminShell.this.gotResponse = true;
                        QSAdminShell.this.multilineResponse = false;
                    }
                }

                try {
                    QSAdminShell.this.clientSocket.close();
                    QSAdminShell.this.clientSocket = null;
                } catch (Exception var3) {
                    QSAdminShell.logger.fine(QSAdminShell.this.error + var3.getMessage());
                }

            }
        };
        t.setDaemon(true);
        t.setName("GUIAdminShell-SocketListener");
        t.start();
    }

    public static void tryFullThreadDump() {
        System.out.println("Trying to get Full Thread Dump @ " + new Date());
        String os = System.getProperty("os.name");
        Robot robot;
        if (os != null && os.toLowerCase().startsWith("windows")) {
            try {
                robot = new Robot();
                robot.keyPress(17);
                robot.keyPress(3);
                robot.keyRelease(3);
                robot.keyRelease(17);
            } catch (Exception var3) {
                logger.warning("Could not press: Ctrl+Break");
            }
        } else {
            try {
                robot = new Robot();
                robot.keyPress(17);
                robot.keyPress(92);
                robot.keyRelease(92);
                robot.keyRelease(17);
            } catch (Exception var2) {
                logger.warning("Could not press: Ctrl+\\");
            }
        }

    }
}
